/** 
 * @file	msp_lib.c
 * @brief	
 * 
 *  This file implements interfaces of module and dynamic library.
 * 
 * @author	hlli
 * @version	1.0
 * @date	2010-05-17
 * 
 * @see		
 * 
 * <b>History:</b><br>
 * <table>
 *  <tr> <th>Version	<th>Date		<th>Author	<th>Notes</tr>
 *  <tr> <td>1.0		<td>2010-05-17	<td>hlli	<td>Create this file</tr>
 * </table>
 * 
 */
#include "os.h"
#include "msp_lib.h"

MSP_LIBHANDLE msp_LoadLibrary( const char* lib_name )
{
#if defined(WINCE)
	wchar_t lib_namew[MAX_PATH];
	size_t len;
	len = mbstowcs(lib_namew, lib_name, msp_strlen(lib_name));
	lib_namew[len] = L'\0';
	return LoadLibraryW( lib_namew );
#elif defined(WIN32)
	return LoadLibrary( lib_name );
#elif !defined(_ANDROID)
	return dlopen(lib_name, RTLD_LAZY);
#endif
}

int msp_FreeLibrary( MSP_LIBHANDLE lib_handle )
{
#if defined(WIN32) || defined(WINCE)
	return FreeLibrary( lib_handle );
#elif !defined(_ANDROID)
	dlclose(lib_handle);
	return 1;
#endif
}

void* msp_GetProcAddress( MSP_LIBHANDLE lib_handle, const char* fun_name )
{
#if defined(WINCE)
	return (void *)GetProcAddressA( lib_handle, fun_name );
#elif defined(WIN32)
	return (void *)GetProcAddress( lib_handle, fun_name );
#elif !defined(_ANDROID)
	return dlsym(lib_handle, fun_name);
#endif
}

MSP_MODULEHANDLE msp_GetModuleHandle( const char* module_name )
{
#if defined(WINCE)
	wchar_t module_namew[MAX_PATH];
	size_t len;
	len = mbstowcs(module_namew, module_name, msp_strlen(module_name));
	module_namew[len] = L'\0';
	return GetModuleHandleW( module_namew );
#elif defined(WIN32)
	return GetModuleHandle( module_name );
#else
	return 0;
#endif
}

int msp_GetModuleFileName( MSP_MODULEHANDLE module_handle, char* module_name, unsigned int name_max_size )
{
#if defined(WINCE)
	wchar_t module_namew[MAX_PATH];
	size_t len;
	len = GetModuleFileNameW( module_handle, module_namew, name_max_size );
	if ( len <= 0 )
		return GetLastError ();
	len = wcstombs(module_name, module_namew, len);
	module_name[len] = '\0';
	return len;
#elif defined(WIN32)
	return GetModuleFileName( module_handle, module_name, name_max_size );
#else
	int ret = readlink("/proc/self/exe", module_name, name_max_size);
	if ( ret == -1 || ret == 0 )
		return 0;
	else
		module_name[ret] = 0;
	return msp_strlen(module_name);
#endif
}
